import { ChangeDetectorRef, Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFComponent, SFSchema, SFUISchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef, NzModalService } from 'ng-zorro-antd';
import { UtilService } from '@core/services/util.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
declare var QRCode


@Component({
  selector: 'app-pay-money',
  templateUrl: './pay-money.component.html',
  styleUrls:['./payMoney.css']
})
export class PayMoneyComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf!: SFComponent;
  @Input()type: 0 | 1;
  @Input()id:string
  @Input()
  set _param(value) {
    if (!value) return;
    this.param = value;
    console.log(this.param);
    if(this.param.openStatus){
      this.openStatus="已开通"
      this.initDate = this.param.useStartTime
      this.selectedDate = this.param.useEndTime
    }else{
      this.initDate = this.getNowDate()
    }
    
    
  };
  validateForm!: FormGroup;
  param: any;
  initDate:any; //用户进入此页面时的到期时间，如果小区并未开通，则此时间为当前时间
  selectedDate:any;//用户选择年数之后根据年数生成的最终时间
  costName:string
  costMoney:number = 0 // 费用金额/年
  totalMoney:any = 0// 总金额  
  yearsTime:any=1 //缴费年限
  costList:any=[];
  openStatus:string="未开通"
  yearList:any =[
    {
      value:"1年",
      code:1,
      selected:false,
    },
    {
      value:"2年",
      code:2,
      selected:false,
    },
    {
      value:"3年",
      code:3,
      selected:false,
    },
  ]

  submitForm(data) {
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsDirty();
      this.validateForm.controls[key].updateValueAndValidity();
      if(this.validateForm.controls[key].invalid){
        return;
      }
    }
    if(this.totalMoney == 0){
      this.msg.error("请选择缴费年限")
      return
    }
    const userObj = JSON.parse(this.util.getStorage("userNow"))
    const body: any = {
      payWay : "3",
      itemId : data.costName,
      payCodingId:this.param.id,
      // payMoney : this.totalMoney * 100,
      personId:userObj.id,
      yearsTime: this.yearsTime,
      businessType:1,
      createBy:userObj.userName,
      createId:userObj.id,
      startTime:this.initDate,
      endTime:this.selectedDate
    }
    console.log(body)
    // /pay/info/qrCodeNativePayment
    this.http.request<any>("post", "/core/qr/pay/qrCodeNativePayment", {body}).subscribe(res => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        let url=res.data;
        const modal = this.modal.create({
          nzTitle: '付款码',
          nzContent: '<div class="qrcode"></div>',
          nzWidth: 400,
          nzFooter: [
            {
              label:"支付完成",
              type:"primary",
              onClick:()=>{
                 modal.close();
                 this.modalRef.triggerOk();
              }
            }
          ],
        })
        modal.afterOpen.subscribe(()=>{
          new QRCode(document.getElementsByClassName("qrcode")[0],{
            width:350,
            height:350
          }).makeCode(url);
        })
      } else {
        this.msg.error(res.message)
      }
    })

  }

  //费用项下拉框option改变
  costChange(value:string):void{
    this.costMoney = this.costList.filter(item=>{
      return item.id == value
    })[0].rentMoney
    let arr = this.yearList.filter(item=>{
      return item.selected
    })
    if(arr.length != 0){
      this.totalMoney = arr[0].code * this.costMoney
    }
  }
  //查询小区费用项
  queryCostListByArea(){
    this.http.request<any>("post", "/core/qr/pay/paymentByAreaId", {body:{itemType:3,areaId:[this.param.id]}}).subscribe(res => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        let arr = res.data.filter(item=>{
          return item.openType == 1
        })
        this.costList = arr.map(item=>{
          return {"costName":item.itemName,"id":item.id,"rentMoney":item.monthlyRent / 100}
        })
        console.log(this.costList)
      } else {
        this.msg.error(res.message)
      }
    })
  }

  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    for (const key in this.validateForm.controls) {
      this.validateForm.controls[key].markAsPristine();
      this.validateForm.controls[key].updateValueAndValidity();
    }
  }

    //点击有效期时长
    yearClick(item:any,i:any):void{
      for(let index in this.yearList){
        if(index == i){
          this.yearList[index].selected=true;
        }else{
          this.yearList[index].selected=false;
        }
      }
        this.yearsTime = item.code
        let num=item.code * 12;
        //根据选择的年数计算最终的到期时间
        this.selectedDate = this.getXuDate(num)
        this.totalMoney =this.costMoney * item.code
        this.totalMoney = this.totalMoney.toFixed(2)
    }
  //根据选择的年数计算最终的到期时间
  getXuDate(num:number){
    let arr =""
    if(this.param.openStatus){
       arr=this.param.useEndTime.split("-");
    }else{
       arr=this.initDate.split("-");
    }
    let nowYear=parseInt(arr[0]);
    let nowMonth:any=parseInt(arr[1]);
    let nowDay:any=parseInt(arr[2]);
    let futureMonth=nowMonth + num;
    if(futureMonth / 12 > 1){
      nowYear+=Math.floor(futureMonth/12);//向下取整
      nowMonth=futureMonth % 12;      
    }else{
      nowMonth+=num;      
    }
    nowMonth = nowMonth < 10 ? "0"+nowMonth : nowMonth
    nowDay = nowDay < 10 ? "0"+nowDay : nowDay
    return nowYear+"-"+nowMonth+"-"+nowDay;
  }

    //获取当前日期
  getNowDate(){
    let date=new Date();
    let year=date.getFullYear();
    let month:any=date.getMonth() + 1;
    let day:any=date.getDate();
    if(month < 10){
      month ="0"+month;
    }
    if(day<10){
      day="0"+day;
    }
    return year+"-"+month+"-"+day;
  }

  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private modal: NzModalService,
    private util: UtilService,
    private ref: ChangeDetectorRef,
    private fb: FormBuilder
  ) { }

 ngOnInit() {
    this.validateForm = this.fb.group({
      costName: [this.costName, [Validators.required]],
    });
    
    this.queryCostListByArea()
  }
}
